<template>
  <div>
    <!-- 月度终端量查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="qjhSalesQuery"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <!-- <Drawer :visible.sync="visible" :title="drawerTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :type="handleType" :rowData="formData" @close="emitCloseHandler" />
    </Drawer> -->
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getLevelOneArea } from '@/api/cms-common/dealerdata/index';
import { monthTerminalQueryList, monthTerminalQueryListExcel, exporturl } from '@/api/omSale/ActualSales/SalesQuery';
import { exportFile } from '@/utils/index';
import { region } from '@/api/cms-common/region';

export default {
  mixins: [dictionary, region],

  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: monthTerminalQueryList,
      fetchParams: {},
      formData: {},
      exportLoading: false,
      visible: false,
      isDealer: false,
      handleType: '',
      drawerTitle: ''
    };
  },
  // components: {
  //   SonModel,
  // },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    //初始化所属区域数据
    this.getTopLevelArea();
    //初始化省份数据
    this.initProvince();
  },
  created() {

  },
  methods: {
    // 导出
    async exportHandle() {
      // let json = Object.assign({}, { CODE: 'CODE_0000007' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          monthTerminalQueryListExcel(this.fetchParams)
            .then(response => {
              debugger;
              if (response.headers.code == '500') {
                this.$notify.error({ title: '提示信息', message: '数据已超过20000，无法导出，请分批次导出数据' });
              } else {
                exportFile(response.data, '月度终端量查询导出', 'xls');
              }
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },

    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },


    emitCloseHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },

    changeHandle(params) {
      // let vin = params.vin;
      let checkDateStart = params.checkDateStart;
      let checkDateEnd = params.checkDateEnd;
      // if (vin == null && checkDateStart == null && checkDateEnd == null) {
      //   this.$notify.error({ title: '提示信息', message: '您好，请您至少填加VIN或者实销通过日期任意一个条件，添加后再次查询。' });
      //   return;
      // }

      var dateBegin = new Date(checkDateStart);
      var dateEnd = new Date(checkDateEnd);
      var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
      var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
      if (dayDiff > 732) {
        this.$notify.error({ title: '提示信息', message: '您好，实销通过日期请不要超过两年。' });
        return;
      }

      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    // 所属区域
    async getTopLevelArea() {
      const res = await getLevelOneArea(15061015);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'areaId').itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },

    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (props) => this.initCity(props),
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '查询多个请使用‘,’分隔',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'RANGE_DATE',
          label: '统计时间',
          fieldName: 'createdDateBegin|createdDateEnd',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange',
        },
        {
          type: 'TEXT_AREA',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '输入多个VIN时，请用英文逗号或者换行隔开（例如：VIN1,VIN2……）',
          maxlength: '',
          maxRows: 2
        },
        {
          type: 'INPUT',
          label: '物料编码',
          fieldName: 'productCode',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '物料描述',
          fieldName: 'productName',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '零售订单号',
          fieldName: 'soNo',
          placeholder: '请输入'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          align: 'center',
          width: 180,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '统计时间',
          dataIndex: 'statisticsTime',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
        },
        {
          title: '零售订单号',
          dataIndex: 'soNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '零售退货单号',
          dataIndex: 'returnSoNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '分配数量',
          dataIndex: 'allocationQuantity',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户手机号',
          dataIndex: 'customerPhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单创建时间',
          dataIndex: 'snCreatedDate',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
        },
        {
          title: '配车时间',
          dataIndex: 'dispatchedData',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
        },
        {
          title: '实际交车时间',
          dataIndex: 'handoverCarTime',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
        },
        {
          title: '终端建档时间',
          dataIndex: 'createdDate',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
        },
        {
          title: '退货完成时间',
          dataIndex: 'returnAccomplishDate',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
        },
        {
          title: '退货原因',
          dataIndex: 'returnRemark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
      ];
    }
  }
};
</script>
